/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        return isBalancedStep(root) == -1 ? false : true;
    }

    int isBalancedStep(TreeNode* root) {
        if(root == nullptr) return 0;
        
        int leftBalanced = isBalancedStep(root->left);
        int rightBalanced = isBalancedStep(root->right);

        if(leftBalanced == -1 || rightBalanced == -1) return -1;
        
        return abs(leftBalanced - rightBalanced) > 1 ? -1 : max(leftBalanced, rightBalanced) + 1;
    }
};